package io.gitee.mingbaobaba.security.core.utils;

import io.gitee.mingbaobaba.security.core.constants.ErrorCodeConstant;
import io.gitee.mingbaobaba.security.core.exception.SecurityBusinessException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.function.Function;

/**
 * <p>读取配置文件工具类</p>
 *
 * @author yingsheng.ye
 * @version 1.0.0
 * @since 2023/8/21 23:00
 */
public class PropertiesUtil {

    private PropertiesUtil() {

    }

    /**
     * 将指定路径的properties配置文件读取到Map中
     * param path 路径
     * return Map<String, String>
     */
    public static final Function<String, Map<String, String>> readPropToMap = path -> {
        Map<String, String> map = new HashMap<>(16);
        try (InputStream inputStream = PropertiesUtil.class.getClassLoader().getResourceAsStream(path)) {
            if (null == inputStream) {
                return new HashMap<>();
            }
            Properties prop = new Properties();
            prop.load(inputStream);
            for (String key : prop.stringPropertyNames()) {
                map.put(key, prop.getProperty(key));
            }
        } catch (IOException e) {
            throw new SecurityBusinessException(ErrorCodeConstant.CODE_CONFIG_FILE_LOAD_ERR,"配置文件(" + path + ")加载失败", e);
        }
        return map;
    };


    /**
     * 将map转换为类对象
     *
     * @param map   map
     * @param clazz 类
     * @param <T>   泛型
     * @return T
     */
    public static <T> T mapToClassObj(Map<String, String> map, Class<T> clazz) {
        ObjectMapper objectMapper = new ObjectMapper();
        T t;
        try {
            String elementStr = objectMapper.writeValueAsString(map);
            t = objectMapper.readValue(elementStr, clazz);
        } catch (Exception e) {
            throw new SecurityBusinessException(ErrorCodeConstant.CODE_CONFIG_FILE_READ_ERR,"属性文件读取异常");
        }
        return t;
    }

}
